import { defineStore } from 'pinia'
import axios from 'axios'
import User from '@/api/user.js'
export const useAuthStore = defineStore('auth', {
    state: () => ({
        token: localStorage.getItem('token') || null,
        user: null,
    }),
    getters: {
        isAuthenticated: (state) => !!state.token
    },
    actions: {
        async login(user) {
            try {
                //打印出user
                console.log(user)
                const response = await User.login(user)
                this.token = response.data.token
                this.user = response.data.user
                console.log(this.user)
                localStorage.setItem('token', this.token)
                return response
            } catch (error) {
                console.error('Login failed:', error)
                return error
            }
        },
        logout() {
            this.token = null
            this.user = null
            localStorage.removeItem('token')
            delete axios.defaults.headers.common['Authorization']
        }
    }
})
